import axios from "axios";
import { jsonToUrl } from "../../utils/index";

let baseURL = process.env.VUE_APP_API_URL; //"https://www.fastmock.site/mock/2495ee95fc429a6d0c761ef4e9f5a696/test";
const api = axios.create({
  baseURL: baseURL,
  timeout: 1000,
  headers: {},
});
api.defaults.headers.post["Content-Type"] = "application/json";

api.post = (url, data, config) => {
  config = config || {};
  return new Promise((resolve, reject) => {
    axios({
      method: "post",
      url: baseURL + url,
      data,
      headers: {
        "Content-Type": "application/json; charset=utf-8",
      },
      ...config,
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

api.get = (url, data, config) => {
  config = config || {};
  url = baseURL + url;
  url = /\?/.test(url)
    ? url + "&" + jsonToUrl(data)
    : url + "?" + jsonToUrl(data);
  return new Promise((resolve, reject) => {
    axios({
      method: "get",
      url: url,
      headers: {
        "Content-Type": "application/json; charset=utf-8",
      },
      ...config,
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

api.delete = (url, data, config) => {
  config = config || {};
  return new Promise((resolve, reject) => {
    axios({
      method: "delete",
      url: baseURL + url,
      headers: {
        "Content-Type": "application/json; charset=utf-8",
      },
      ...config,
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

api.put = (url, data, config) => {
  config = config || {};
  return new Promise((resolve, reject) => {
    axios({
      method: "put",
      url: baseURL + url,
      headers: {
        "Content-Type": "application/json; charset=utf-8",
      },
      ...config,
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

api.interceptors.response.use(
  (response) => {
    //拦截响应，做统一处理
    if (response.data.code) {
      switch (response.status) {
        case 301:
          console.log("登录过期");
      }
    }
    return response;
  },
  //接口错误状态处理，也就是说无响应时的处理
  (error) => {
    return Promise.reject(error.response.status); // 返回接口返回的错误信息
  }
);

export default api;
